// Calculator.hpp
#pragma once
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

// 上层业务
class Calculator
{
public:
    Calculator()
    {
    }
    ~Calculator()
    {
    }

public:
    std::string Handler(std::string &package)
    {
        // package = "len"\n"10 + 20"\n
        std::string content; // 报文的有效载荷
        bool r = Decode(package, &content);
        if (!r)
            return "";
        // content = "10 + 20"

        Request req; // 反序列化
        r = req.Deserialize(content);
        if (!r)
            return "";
        // x=10, op=+, y=20

        // 我们的业务逻辑比较简单，没有特别耗时的操作，这里单进程就直接计算处理了
        // 如果操作复杂，就可以把线程池拿过来，把任务推送到线程池里，交给线程去处理
        // 处理完之后，再由线程池把处理结果交给TcpServer，由TcpServer发出去
        Response resp = HandlerHelper(req); // 计算
        // result=30, code=0

        std::string s;
        resp.Serialize(&s); // 结构体序列化，s = "30 0"
        s = Encode(s);      // 添加报头, s = "len"\n"30 0"\n

        return s;
    }

private:
    Response HandlerHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
            if (req.y != 0)
                resp.result = req.x / req.y;
            else
                resp.code = Div_Zero;
            break;
        case '%':
            if (req.y != 0)
                resp.result = req.x % req.y;
            else
                resp.code = Mod_Zero;
            break;
        default:
            resp.code = Other_Oper;
            break;
        }
        return resp;
    }
};